#Skytank project
#Author: Leo Szeto
#Last updated: 2/8/2011
#Abstract: Skype controlled telepresense robot. Can be ordered to move across terrain wherever wifi is available.

#Dedicated to Michelle, for being my inspiration for this project. 

#Import python libraries
import math
import time

#Import wrapper libraries
import Skype4Py #Netbook -> Internet layer
import serial   #Netbook -> Circuits layer

#Custom Functions
#-----------------------------------------------
#Handshake function
#Attempts to complete a handshake with a device
#Returns the device signature if success, returns -1 if it fails.
def handshake(max_tries):
	max_tries = math.fabs(max_tries) #Makes sure that the attempts value is negative
	tries = 0
	word = -1
	print "Sending info"		
	ser.write("INIT") 					#Send the INIT command to the arduino
	while tries < max_tries:
		print "Attempt #" + str(tries) + "..."
		if ser.inWaiting() >= 4: 		#Wait until there are 4 bytes (At least 1 cmd)
			print "Command returned"
			word = ser.read(4)   		#Read the cmd (4 bytes) 
			tries = max_tries			#We are now done, exit
		else:
			tries = tries + 1
		time.sleep(.25)
	return word 				 		#Return the results back

#Move function
#Attempts to move the vehicle. left and right denote the left and right motors
#and has a range of 0 - 255. 0 - 127 is backwards while 128 - 255 is forwards.
def move_car(left, right):

#LED control
#Attempts to turn on an LED. value denotes the LED that is toggled. 
def LED_ctrl(value):

#Request ID
#Requests for the UID of the arduino. This is used to figure out which USB port has
#which arduino.
def req_ID():



#----------------------------------------------------
#INITIALIZATION - SKYPE
#----------------------------------------------------
#Create an instance of the Skype class
skype = Skype4Py.Skype()

#If skype is not running, go ahead and run it. 
#(DOES NOT WORK) Inquire about that.
if not skype.Client.IsRunning:
	print "Client is not running."
	skype.Client.Start()

#connect to the Skype class, if this is the script's
#first run, it will most likely ask for permission.
skype.Attach()
print "Skype wrapper is now attached."
#----------------------------------------------------
#INITIALIZATION - Serial
#----------------------------------------------------
#Create an instance of the serial class and link it
#to the arduino
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout = 0.5)
print "Starting Serial interface"
time.sleep(2) #2 second delay to allow for arduino to be ready.
#Do some handshaking to ensure that a connection 
#has been made. We should write to the device first.
print "Starting handshake"
cmd = handshake(5)
cmdval = convert_instr(cmd)
if cmd == "ARDY":
	print "Completed, CMD: " + cmd
if cmd == "FAIL":
	print "ERROR: Invalid cmd"
if cmd == -1:
	print "ERROR: Cannot find arduino"
